import Cookies from 'js-cookie'
import { promises } from 'fs';
var session = require('electron').remote.session;

const TokenKey = 'YM_MERCHANT_TOKEN'

export function getToken() {
  return new Promise((resolve, reject) => {
    session.defaultSession.cookies.get({}).then((cookies) => {
      let judge = false
      cookies.forEach(item => {
        if (item.name === TokenKey) {
          const returnCookie = JSON.parse(unescape(item.value.replace(/\\u/g, "%u")));
          judge = true;
          resolve(JSON.stringify(returnCookie))
        }
      })
      if (!judge) {
        resolve(null)
      }
    }).catch((error) => {
      reject(error)
    })
  });
}

export function setToken(token, uid) {
  const auth = {
    token: token,
    uid: uid
  }
  return Cookies.set(TokenKey, auth)
}

export function removeToken() {
  return Cookies.remove(TokenKey)
}
